package com.jsb.laundry.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jsb.laundry.common.constant.CommonConstants;
import com.jsb.laundry.common.exception.BusinessException;
import com.jsb.laundry.common.exception.ErrorCode;
import com.jsb.laundry.common.exception.ThrowUtils;
import com.jsb.laundry.dao.*;
import com.jsb.laundry.model.dto.posts.PostQueryRequest;
import com.jsb.laundry.model.entity.*;
import com.jsb.laundry.model.vo.PostsVO;
import com.jsb.laundry.model.vo.UserVO;
import com.jsb.laundry.service.JsbPostsService;
import com.jsb.laundry.utils.SqlUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author ching
 * @description 针对表【jsb_posts(帖子表)】的数据库操作Service实现
 * @createDate 2023-08-09 14:06:04
 */
@Service
public class JsbPostsServiceImpl extends ServiceImpl<JsbPostsMapper, JsbPosts>
        implements JsbPostsService {
    @Resource
    private JsbPostsMapper postsMapper;

    @Resource
    private UserDetailMapper userDetailMapper;
    @Resource
    private JsbPostLikesMapper postLikeMapper;

    @Resource
    private JsbPostFavoritesMapper postFavourMapper;

    @Resource
    private JsbPostUserFollowersMapper postUserFollowersMapper;

    @Override
    public void validPost(JsbPosts posts, boolean add) {
        if (posts == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String title = posts.getTitle();
        String content = posts.getContent();
        String images = posts.getImages();
        // 创建时，参数不能为空
        if (add) {
            ThrowUtils.throwIf(StringUtils.isAnyBlank(title, content, images), ErrorCode.PARAMS_ERROR);
        }
        // 有参数则校验
        if (StringUtils.isNotBlank(title) && title.length() > 80) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "标题过长");
        }
        if (StringUtils.isNotBlank(content) && content.length() > 8192) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "内容过长");
        }
    }

    @Override
    public QueryWrapper<JsbPosts> getQueryWrapper(PostQueryRequest postQueryRequest) {
        QueryWrapper<JsbPosts> queryWrapper = new QueryWrapper<>();
        if (postQueryRequest == null) {
            return queryWrapper;
        }
        String searchText = postQueryRequest.getSearchText();
        String sortField = postQueryRequest.getSortField();
        String sortOrder = postQueryRequest.getSortOrder();
        String title = postQueryRequest.getTitle();
        String content = postQueryRequest.getContent();
        String userId = postQueryRequest.getUserId();
        // 拼接查询条件
        if (StringUtils.isNotBlank(searchText)) {
            queryWrapper.like("title", searchText).or().like("content", searchText);
        }
        queryWrapper.like(StringUtils.isNotBlank(title), "title", title);
        queryWrapper.like(StringUtils.isNotBlank(content), "content", content);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "user_id", userId);
        queryWrapper.eq("is_del", 0);
        queryWrapper.eq("is_approved", 1);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstants.SORT_ORDER_ASC), sortField);
        return queryWrapper;
    }

    @Override
    public PostsVO getPostVO(String loginUserId, JsbPosts post, HttpServletRequest request) {
        PostsVO postsVO = PostsVO.objToVo(post);
        long postId = post.getId();
        // 1. 关联查询用户信息
        String userId = post.getUserId();
        UserDetail user = new UserDetail();
        if (userId != null && !"".equals(userId)) {
            user = userDetailMapper.findUserDetailByUserId(userId);
        }
        UserVO userVO = new UserVO();
        userVO.setUserId(user.getUserId());
        userVO.setUserName(user.getUserName());
        userVO.setUserAvatar(user.getUserAvatar());
        postsVO.setUser(userVO);
        // 2. 获取用户点赞、收藏状态
        // 获取点赞
        QueryWrapper<JsbPostLikes> postLikesQueryWrapper = new QueryWrapper<>();
        postLikesQueryWrapper.in("post_id", postId);
        postLikesQueryWrapper.eq("user_id", loginUserId);
        JsbPostLikes postlike = postLikeMapper.selectOne(postLikesQueryWrapper);
        postsVO.setHasLike(postlike != null);
        // 获取收藏
        QueryWrapper<JsbPostFavorites> postFavourQueryWrapper = new QueryWrapper<>();
        postFavourQueryWrapper.in("post_id", postId);
        postFavourQueryWrapper.eq("user_id", loginUserId);
        JsbPostFavorites postFavour = postFavourMapper.selectOne(postFavourQueryWrapper);
        postsVO.setHasFavour(postFavour != null);
        // 获取关注
        QueryWrapper<JsbPostUserFollowers> postUserFollowQueryWrapper = new QueryWrapper<>();
        postUserFollowQueryWrapper.in("follower_id", post.getUserId());
        postUserFollowQueryWrapper.eq("user_id", loginUserId);
        JsbPostUserFollowers postUserFollowers = postUserFollowersMapper.selectOne(postUserFollowQueryWrapper);
        postsVO.setHasFollow(postUserFollowers != null);
        return postsVO;
    }

    @Override
    public Page<PostsVO> getPostVOPage(String loginUserId, Page<JsbPosts> postPage, HttpServletRequest request) {
        List<JsbPosts> postList = postPage.getRecords();
        Page<PostsVO> postVOPage = new Page<>(postPage.getCurrent(), postPage.getSize(), postPage.getTotal());
        if (CollectionUtils.isEmpty(postList)) {
            return postVOPage;
        }
        // 填充信息
        List<PostsVO> postVOList = postList.stream().map(post -> {
            PostsVO postVO = PostsVO.objToVo(post);
            String userId = post.getUserId();
            UserDetail user = new UserDetail();
            if (userId != null && !"".equals(userId)) {
                user = userDetailMapper.findUserDetailByUserId(userId);
            }
            UserVO userVO = new UserVO();
            userVO.setUserId(user.getUserId());
            userVO.setUserName(user.getUserName());
            userVO.setUserAvatar(user.getUserAvatar());
            postVO.setUser(userVO);
            // 获取点赞
            QueryWrapper<JsbPostLikes> postLikesQueryWrapper = new QueryWrapper<>();
            postLikesQueryWrapper.in("post_id", post.getId());
            postLikesQueryWrapper.eq("user_id", loginUserId);
            JsbPostLikes postlike = postLikeMapper.selectOne(postLikesQueryWrapper);
            postVO.setHasLike(postlike != null);
            // 获取收藏
            QueryWrapper<JsbPostFavorites> postFavourQueryWrapper = new QueryWrapper<>();
            postFavourQueryWrapper.in("post_id", post.getId());
            postFavourQueryWrapper.eq("user_id", loginUserId);
            JsbPostFavorites postFavour = postFavourMapper.selectOne(postFavourQueryWrapper);
            postVO.setHasFavour(postFavour != null);
            // 获取关注
            QueryWrapper<JsbPostUserFollowers> postUserFollowQueryWrapper = new QueryWrapper<>();
            postUserFollowQueryWrapper.in("follower_id", post.getUserId());
            postUserFollowQueryWrapper.eq("user_id", loginUserId);
            JsbPostUserFollowers postUserFollowers = postUserFollowersMapper.selectOne(postUserFollowQueryWrapper);
            postVO.setHasFollow(postUserFollowers != null);
            return postVO;
        }).collect(Collectors.toList());
        postVOPage.setRecords(postVOList);
        return postVOPage;
    }

    @Override
    public int getLikesReceivedNum(String userId) {
        int likesReceivedNum = 0;
        likesReceivedNum = postsMapper.getLikesReceivedNum(userId);
        return likesReceivedNum;
    }
}




